package br.com.foxline.atlasmobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;
import br.com.foxline.atlasmobile.util.SharedPreference;

public class ShowCadastroActivity extends Activity {

	private static String IMOVEL = "getimovel";
	private ImovelDao imovelDao;

	private ListView list;
	private ImovelArrayAdapter arrayAdapter;
	private Imovel imovel;
	private ActionBar actionBar;
	private int saveOpc = 0;
	private ProgressDialog dialog;
	
	int current_page = 0;

	private OnItemLongClickListener listener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {

			imovel = arrayAdapter.getItem(arg2);
			imovel = imovelDao.find(imovel.getId());

			Intent intent = new Intent(getApplicationContext(),
					CreateMainActivity.class);

			intent.putExtra(IMOVEL, imovel);
			startActivity(intent);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			finish();

			return false;
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show_cadastro);

		imovelDao = new ImovelDao(getApplicationContext());

		list = (ListView) findViewById(R.id.listShow);

		//btn Carregar mais
		Button btnLoadMore = new Button(this);
		btnLoadMore.setText("Carregar mais");
		 
		btnLoadMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {

				
				SearchImovel searchImovel = new SearchImovel(
						list.getContext());
				searchImovel.execute(saveOpc);
			}
		});
		
		list.addFooterView(btnLoadMore);
		
		arrayAdapter = new ImovelArrayAdapter(getApplicationContext());

		list.setAdapter(arrayAdapter);
		list.setOnItemLongClickListener(listener);

		TextView emptyView = (TextView) findViewById(android.R.id.empty);
		emptyView.setText(R.string.empty);
		list.setEmptyView(emptyView);
		
		
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		case R.id.search_cadastro:
			if (actionBar.getSelectedNavigationIndex() != 4) {
				saveOpc = actionBar.getSelectedNavigationIndex();
				actionBar.setSelectedNavigationItem(4);

			} else {
				showDialogSearch();
			}
			break;
		}
		return true;
	}

	public Integer parseInt(String str) {
		if (str != null && !str.equals(""))
			return Integer.parseInt(str);
		return null;

	}

	public void showDialogSearch() {
		LayoutInflater inflater = this.getLayoutInflater();
		final View inflate = inflater.inflate(
				R.layout.activity_search_cadastro, null);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pesquisar");
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				Integer inscricaoCadastralD = parseInt(((EditText) inflate
						.findViewById(R.id.search_insc_d)).getText().toString());
				Integer inscricaoCadastralS = parseInt(((EditText) inflate
						.findViewById(R.id.search_insc_s)).getText().toString());
				Integer inscricaoCadastralQuadra = parseInt(((EditText) inflate
						.findViewById(R.id.search_insc_quadra)).getText()
						.toString());
				Integer inscricaoCadastralLote = parseInt(((EditText) inflate
						.findViewById(R.id.search_lote)).getText().toString());
				Integer inscricaoCadastralUnid = parseInt(((EditText) inflate
						.findViewById(R.id.search_insc_unid)).getText()
						.toString());
				String logradouro = ((EditText) inflate
						.findViewById(R.id.search_logradouro)).getText()
						.toString();
				Integer numero = parseInt(((EditText) inflate
						.findViewById(R.id.search_numero)).getText().toString());
				String proprietario = ((EditText) inflate
						.findViewById(R.id.search_proprietario)).getText()
						.toString();

				List<Imovel> findInscricao = imovelDao.findInscricao(
						inscricaoCadastralD, inscricaoCadastralS,
						inscricaoCadastralQuadra, inscricaoCadastralLote,
						inscricaoCadastralUnid, logradouro, numero,
						proprietario);

				arrayAdapter.setList(findInscricao);
				arrayAdapter.notifyDataSetChanged();

			}
		});

		builder.setNegativeButton("Cancelar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						actionBar.setSelectedNavigationItem(saveOpc);
					}
				});

		builder.setView(inflate);
		AlertDialog dlg = builder.create();
		dlg.show();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_show_cadastro, menu);

		actionBar = getActionBar();

		TextView view = new TextView(getApplicationContext());
		view.setText(" Filtro ");
		actionBar.setCustomView(view);
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		OnNavigationListener naviga = new OnNavigationListener() {
			@Override
			public boolean onNavigationItemSelected(int itemPosition,
					long itemId) {
				if (itemPosition < 4) {
					saveOpc = itemPosition;
					current_page = 0;
					SearchImovel searchImovel = new SearchImovel(
							list.getContext());
					searchImovel.execute(itemPosition);
				} else {
					showDialogSearch();
				}

				return false;
			}

		};

		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("Imóveis Recentes");
		arrayList.add("Meus Imóveis");
		arrayList.add("Imóveis Concluídos");
		arrayList.add("Imóveis Pendentes");
		arrayList.add("Personalizada");

		actionBar.setListNavigationCallbacks(new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_list_item_1,
				android.R.id.text1, arrayList), naviga);

		return true;
	}

	private class ImovelArrayAdapter extends ArrayAdapter<Imovel> {

		private List<Imovel> list;
		private Context context;

		public ImovelArrayAdapter(Context context) {
			super(context, R.layout.imovel_item);
			this.context = context;
			list = new ArrayList<Imovel>();
		}

		public void setList(List<Imovel> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Imovel getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return super.getItemId(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View rowView = inflater
					.inflate(R.layout.imovel_item, parent, false);

			Imovel imovel = list.get(position);

			TextView inscri = (TextView) rowView
					.findViewById(R.id.show_inscricao);
			TextView endereco = (TextView) rowView
					.findViewById(R.id.show_endereco_imovel);
			TextView grupo = (TextView) rowView.findViewById(R.id.show_grupo);
			TextView situacao = (TextView) rowView
					.findViewById(R.id.show_situacao);

			String string = "#" + imovel.getId() + " - "
					+ imovel.getInscricaoCadastralD() + "."
					+ imovel.getInscricaoCadastralS() + "."
					+ imovel.getInscricaoCadastralQuadra() + "."
					+ imovel.getInscricaoCadastralLote() + "."
					+ imovel.getInscricaoCadastralUnid();

			inscri.setText(string.replace("null", "0"));
			SimpleDateFormat formar = new SimpleDateFormat("dd/MM/yyyy HH:mm");
			endereco.setText(imovel.toString());
			grupo.setText(imovel.getGroupCreate());
			situacao.setText((imovel.getSituacaoImovel() == null ? "" : imovel
					.getSituacaoImovel().toString())
					+ (imovel.getEnviado() != null && imovel.getEnviado() ? (imovel
							.getDateenviado() != null ? " - Enviado em "
							+ formar.format(imovel.getDateenviado()) : "")
							: ""));

			if (imovel.getSituacaoImovel() == SituacaoImovel.CONCLUIDO)
				situacao.setTextColor(Color.rgb(20, 100, 20));
			else if (imovel.getSituacaoImovel() == SituacaoImovel.CANCELADO)
				situacao.setTextColor(Color.YELLOW);
			else if (imovel.getSituacaoImovel() == SituacaoImovel.PENDENTE_DOC
					|| imovel.getSituacaoImovel() == SituacaoImovel.PENDENTE_PROPRIETARIO
					|| imovel.getSituacaoImovel() == SituacaoImovel.PENDENTE_RECUSADO)
				situacao.setTextColor(Color.RED);
			return rowView;
		}

	}

	private class SearchImovel extends AsyncTask<Integer, Void, List<Imovel>> {

		private Context context;

		private SearchImovel(Context context) {
			super();
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = ProgressDialog.show(context, "", "Carregando Registros..",
					true);

		}

		public List<Imovel> all() {
			return imovelDao.findPaginatorAll(Long.parseLong(current_page+""), 0l);
		}

		public List<Imovel> myProperties() {
			SharedPreferences prefs = context.getSharedPreferences(
					SharedPreference.PREFS_NAME, 0);
			return imovelDao.myProperties(prefs.getString(
					SharedPreference.GROUPS, ""), Long.parseLong(current_page+""), 0l);
		}

		public List<Imovel> pending() {
			return imovelDao.pending(Long.parseLong(current_page+""), 0l);
		}

		public List<Imovel> completed() {
			return imovelDao.completed(Long.parseLong(current_page+""), 0l);
		}

		protected List<Imovel> doInBackground(Integer... urls) {
			
			current_page += 8;
			
			switch (urls[0]) {
			case 0:
				return all();
			case 1:
				return myProperties();
			case 2:
				return completed();
			case 3:
				return pending();
			default:
				break;
			}

			return all();
		}

		protected void onPostExecute(List<Imovel> result) {
			arrayAdapter.setList(result);
			arrayAdapter.notifyDataSetChanged();
			list.setSelectionFromTop(current_page-5, 0);
			dialog.dismiss();
		}
	}

}
